package com.oocl.customer.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.customersystem.pojo.Order;
import com.oocl.customersystem.util.RequestUtil;

/**
 * Servlet implementation class AddOrders
 */
public class AddOrders extends HttpServlet {
private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foodName = request.getParameter("foodName");
		String priceStr = request.getParameter("price");
		
		int price = Integer.parseInt(priceStr);
		Map<String,Order> cart = (Map<String, Order>) request.getSession().getAttribute("cart");
		if(null==cart){
			cart = new HashMap<String,Order>();
		}
		Order o = cart.get(foodName);
		if(null==o){
			o = new Order();
			o.setPrice(price);
			o.setCount(1);
			o.setName(foodName);
			int id =(int) (Math.random()*10000);
			o.setId(id);
		}else{
			o.setCount(o.getCount()+1);	
		}
		cart.put(foodName, o);
		request.getSession().setAttribute("cart", cart);
		List<Order> list =new  ArrayList<Order>();
		Set<String> set = cart.keySet();
		for(String name:set){
			list.add(cart.get(name));
		}
		String json = RequestUtil.wrapToJson(list);
		response.setContentType("application/json;charset=utf-8");
		response.getWriter().write(json);
	}

}
